interface RequestOptions {
  url: string;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  data?: any;
  header?: any;
}

interface ResponseData<T = any> {
  code: number;
  data: T;
  message: string;
}

const BASE_URL = 'http://localhost:3000'; // 替换为实际的API地址

class Request {
  private static instance: Request;
  
  private constructor() {}
  
  public static getInstance(): Request {
    if (!Request.instance) {
      Request.instance = new Request();
    }
    return Request.instance;
  }

  // 请求拦截器
  private beforeRequest(options: RequestOptions) {
    const token = uni.getStorageSync('token');
    if (token) {
      options.header = {
        ...options.header,
        'Authorization': `Bearer ${token}`
      };
    }
    return options;
  }

  // 响应拦截器
  private handleResponse(response: any) {
    if (response.statusCode === 401) {
      // token过期，清除登录状态
      uni.removeStorageSync('token');
      uni.showToast({
        title: '登录已过期，请重新登录',
        icon: 'none'
      });
      // 跳转到登录页
      uni.navigateTo({
        url: '/pages/login/login'
      });
      return Promise.reject(response);
    }
    
    if (response.statusCode !== 200) {
      uni.showToast({
        title: response.data.message || '请求失败',
        icon: 'none'
      });
      return Promise.reject(response);
    }
    
    return response.data;
  }

  public request<T>(options: RequestOptions): Promise<ResponseData<T>> {
    options.url = `${BASE_URL}${options.url}`;
    options = this.beforeRequest(options);

    return new Promise((resolve, reject) => {
      uni.request({
        ...options,
        success: (response) => {
          resolve(this.handleResponse(response));
        },
        fail: (error) => {
          uni.showToast({
            title: '网络请求失败',
            icon: 'none'
          });
          reject(error);
        }
      });
    });
  }

  public get<T>(url: string, data?: any): Promise<ResponseData<T>> {
    return this.request<T>({
      url,
      method: 'GET',
      data
    });
  }

  public post<T>(url: string, data?: any): Promise<ResponseData<T>> {
    return this.request<T>({
      url,
      method: 'POST',
      data
    });
  }

  public put<T>(url: string, data?: any): Promise<ResponseData<T>> {
    return this.request<T>({
      url,
      method: 'PUT',
      data
    });
  }

  public delete<T>(url: string, data?: any): Promise<ResponseData<T>> {
    return this.request<T>({
      url,
      method: 'DELETE',
      data
    });
  }
}

export const http = Request.getInstance(); 